<?php

namespace app\api\model;

use app\admin\event\SystemLog;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class CustomerCategory extends Model
{

    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    use CanGetFieldModel, SimplePaginate;
    protected $table = 'jxc_customer_category';
    protected $field = ['id', 'name', 'discount', 'des'];

    /**
     * @return \think\model\relation\HasMany
     */
    public function user()
    {
        return $this->hasMany(UserModel::class, 'category');
    }


    /**
     * 客户分类 列表
     * @param $data
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     * @throws DbException
     */
    public function getList($data, $page = 1, $size = 10)
    {
        return $this->page($page, $size)->paginate($size);
    }

    /**
     * 客户分类 新增
     * @param $data
     * @return int|string
     */
    public function getAdd($data)
    {
        return $this::create($data);
    }

    /**
     * 客户分类 查找
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getCategory($id)
    {
        try {
            return $this->findOrFail($id);
        } catch (DataNotFoundException $e) {
            return $e->getMessage();
        } catch (ModelNotFoundException $e) {
            return $e->getMessage();
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * 客户分类 修改
     * @param $id
     * @param $data
     * @return int|string
     */
    public function getEdit($id, $data)
    {
        try {
            return $this->where('id', $id)->update($data);
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    /**
     * 客户分类 删除
     * @param $id
     * @return int
     */
    public function getDel($id)
    {
        try {
            return $this->where('id', $id)->delete();
        } catch (PDOException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}
